﻿using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace WebStore.Domain.Entities
{
    public partial class Entities
    {
        protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
            var configurations = FindDerivedTypes(Assembly.GetExecutingAssembly(), typeof(EntityTypeConfiguration<>));
            foreach (var configuration in configurations)
            {
                dynamic configurationInstance = Activator.CreateInstance(configuration);
                modelBuilder.Configurations.Add(configurationInstance);
            }
            base.OnModelCreating(modelBuilder);
        }

        private IEnumerable<Type> FindDerivedTypes(Assembly assembly, Type baseType)
        {
            return assembly.GetTypes()
            .Where(t => t.BaseType != null && (t.BaseType.IsGenericType &&
                                               t.BaseType.GetGenericTypeDefinition() == baseType));
        }
    }
}
